#!/usr/bin/env node
const Client = require("ssh2-sftp-client");
const fs = require("fs");
const path = require("path");

const localFolderPath = "./dist";

function readConfig() {
  try {
    const res = path.resolve("bzip.config.json");
    const info = fs.readFileSync(res, "utf-8");
    return info;
  } catch (error) {
    console.log("配置文件读取失败", error);
  }
}

async function checkFolderExistence(folderPath) {
  try {
    await fs.promises.access(folderPath);
    return true;
  } catch (error) {
    if (error.code === "ENOENT") {
      return false;
    } else {
      throw error; // 重新抛出其他类型的错误
      return false;
    }
  }
}

function isDeepEqual(obj1, obj2) {
  if (obj1 === obj2) return true;

  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
      return false;
  }

  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) {
      return false;
  }

  for (let key of keys1) {
      if (!keys2.includes(key) || !isDeepEqual(obj1[key], obj2[key])) {
          return false;
      }
  }

  return true;
}


async function main() {
  const ora = await import('ora');
  const bzipConfig = JSON.parse(readConfig());
  const config = {
    host: bzipConfig.host,
    port: bzipConfig.port,
    username: bzipConfig.username,
    password: bzipConfig.password,
  };

  const defaultConfig = {
    name: "bzip",
    host: "111.222.333.444",
    port: "22",
    username: "Admin",
    password: "xxxyyyzzz111222333444",
    remoteFolderPath: "c:/test/dist",
  };

  if (isDeepEqual(bzipConfig,defaultConfig)) {
    console.log("请配置bzip.config.json文件");
    return;
  }

  const isDist = await checkFolderExistence(localFolderPath);
  if (!isDist) {
    console.log("本地dist文件夹不存在");
    return;
  }

  const remoteFolderPath = bzipConfig.remoteFolderPath;

  const spinner = ora.default("自动发布脚本开始执行").start();
  const sftp = new Client(); // 实例化用于调用其自带的方法

  try {
    spinner.text = "正在连接服务器...";
    await sftp.connect(config);
    spinner.text = "连接服务器成功";
    const dirExists = await sftp.exists(remoteFolderPath);
    if (dirExists) {
      spinner.text = "旧的dist文件夹删除...";
      await sftp.rmdir(remoteFolderPath, true); // 把旧的dist删除掉
      spinner.text = "旧的dist文件夹删除成功";
    }
    spinner.text = "新的dist文件夹上传...";
    await sftp.uploadDir(localFolderPath, remoteFolderPath); // 新的dist删除掉
    spinner.text = "新的dist文件夹上传成功";
  } catch (error) {
    spinner.fail("自动发布脚本执行失败");
  } finally {
    spinner.info("自动发布脚本执行完毕");
  }
}

main();
